import shell from "shelljs";
import chalk from "chalk";
import fs from "fs";
import fse from "fs-extra";
import path from "path";
import { fileURLToPath } from "url";

const SOURCE_DIR = "../dist";
// const DEST_DIR = 'test'
const DEST_DIR = "~/www/wwwroot/lixingxing.shop/math";

const request = async (str) => {
  // axios.post("https://open.feishu.cn/open-apis/bot/v2/hook/423e8d45-a4eb-4631-9bbc-b9d66b0c5b42", {
  //   msg_type: "text",
  //   content: { text: str },
  // });
};

// 删除 node_modules
const delNodeModules = async () => {
  const res = shell.exec("rimraf.cmd ./node_modules/");
  if (res.code === 0) {
    console.log(chalk.green("node_modules 删除成功"));
  } else {
    request("node_modules 删除失败");
  }
};

// 安装模块
const install = async () => {
  const res = shell.exec("cnpm i");
  if (res.code === 0) {
    console.log(chalk.green("cnpm i 安装成功"));
  } else {
    request("cnpm i 安装失败");
  }
};

// 打包
const build = async () => {
  const res = shell.exec("cnpm run build");
  if (res.code === 0) {
    console.log(chalk.green("cnpm run build 成功"));
  } else {
    request("cnpm run build 失败");
  }
};

// 发布
const publish = async () => {
  const __filenameNew = fileURLToPath(import.meta.url);
  const __dirnameNew = path.dirname(__filenameNew);
  const sourceDir = path.join(__dirnameNew, SOURCE_DIR);
  const destDir = path.join(__dirnameNew, DEST_DIR);
  if (!fs.existsSync(destDir)) {
    fs.mkdirSync(destDir, { recursive: true });
  }
  console.log('%c' + 'sourceDir', 'background: green; color: #fff;')
  console.log(sourceDir)
  console.log(destDir)
  // copy directory content including subfolders
  fse.copy(sourceDir, destDir, function (err) {
    if (err) {
      console.error(err);
      console.log(chalk.red("发布失败"));
      request("发布失败");
    } else {
      console.log(chalk.green("发布成功"));
      request("发布成功");
    }
  });
};

async function runTask() {
  // await delNodeModules();
  await install();
  await build();
  await publish();
}
runTask();
